<template>
  <view class="cart-page">
    <!-- 按超市分组展示购物车商品 -->
    <view
      v-for="(supermarketGroup, supermarketIndex) in groupedCartlist"
      :key="supermarketIndex"
      class="supermarket-group"
    >
      <!-- 显示超市名称和该超市商品的总价 -->
      <view class="supermarket-header">
        <checkbox-group @change="toggleSupermarketSelect(supermarketGroup)">
          <label>
            <checkbox :checked="isSupermarketSelected(supermarketGroup)" />
            <text class="supermarket-name">{{
              supermarketGroup[0].shopName
            }}</text>
          </label>
        </checkbox-group>
        <text @click="clearCurrentSupermarketCart(supermarketGroup)"
          >清空购物车</text
        >
     
      </view>

      <view
        class="cart-item"
        v-for="(item, itemIndex) in supermarketGroup"
        :key="itemIndex"
      >
        <checkbox-group @change="toggleItemSelect(item)">
          <label>
            <checkbox :checked="item.selected" />
          </label>
        </checkbox-group>
        <image
          class="cart-item-img"
          :src="item.imgUrl"
          mode="aspectFill"
        ></image>
        <view class="cart-item-info">
          <view class="item-name">{{ item.name }}</view>
          <view class="item-price">单价: ￥{{ item.price.toFixed(2) }}</view>
          <view class="item-quantity">
            <text class="quantity-btn" @click="debouncedDecreaseQuantity(item)"
              >-</text
            >
            <text class="quantity-num">{{ item.quantity }}</text>
            <text class="quantity-btn" @click="debouncedIncreaseQuantity(item)"
              >+</text
            >
          </view>
        </view>
        <view class="item-subtotal"
          >￥{{ (item.price * item.quantity).toFixed(2) }}</view
        >
        <uni-icons
          class="delete-btn"
          type="trash"
          size="20"
          @click="removeItem(item)"
        ></uni-icons>

        
      </view>
      <view>
           <view class="supermarket-total">
            <view style="line-height:60px;font-size:20px">总价: ￥{{ calculateSupermarketTotal(supermarketGroup).toFixed(2) }}</view>
            <view style="height:45px;margin:10px" >
              <button
                  type="primary"
                 @click="checkoutBySupermarket(supermarketGroup)"
              >
                  结算
              </button>
            </view>
             
            
        </view>
      </view>
      
    </view>

    <!-- <view class="checkout-bar">
      <view class="total-price"> 总计: ￥{{ totalPrice.toFixed(2) }} </view>
      <view class="checkout-button" @click="checkout">
        去结算({{ totalQuantity }})
      </view>
    </view> -->

    <view v-if="cartlist.length === 0" class="empty-cart">
      <uni-icons type="cart" size="60" color="#999"></uni-icons>
      <view class="empty-text">购物车是空的</view>
      <view class="empty-text">快去挑选商品吧~</view>
    </view>
  </view>
</template>

<script>
	import Config from '@/Config.js'
	// import  Config from @api_host 
// 防抖函数
function debounce(func, delay) {
  let timer;
  return function (...args) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      func.apply(this, args);
      timer = null;
    }, delay);
  };
}

export default {
  data() {
    return {
      cartlist: [],
      // 用于存储防抖后的方法
      debouncedIncreaseQuantity: null,
      debouncedDecreaseQuantity: null,
    };
  },

  computed: {
    // 按超市分组购物车商品
    groupedCartlist() {
      const grouped = {};
      this.cartlist.forEach((item) => {
        if (!grouped[item.shopId]) {
          grouped[item.shopId] = [];
        }
        grouped[item.shopId].push(item);
      });
      return Object.values(grouped);
    },
    // 计算总价 - 只计算选中的商品
    totalPrice() {
      return this.cartlist.reduce((total, item) => {
        return item.selected ? total + item.price * item.quantity : total;
      }, 0);
    },
    // 计算总数量 - 只计算选中的商品
    totalQuantity() {
      return this.cartlist.reduce((total, item) => {
        return item.selected ? total + item.quantity : total;
      }, 0);
    },
    // 是否全选
    isAllSelected() {
      return (
        this.cartlist.length > 0 && this.cartlist.every((item) => item.selected)
      );
    },
  },
  onShow() {
    this.loadCartData();
    // 初始化防抖函数
    this.debouncedIncreaseQuantity = debounce(this.increaseQuantity, 300);
    this.debouncedDecreaseQuantity = debounce(this.decreaseQuantity, 300);
  },
  methods: {
    loadCartData() {
      const userId = uni.getStorageSync('userId');
      uni.request({
        url: Config.api_host+`/users/${userId}`,
        success: (res) => {
          if (res.data && res.data.cart) {
            this.cartlist = res.data.cart;
            // 确保每个商品都有selected属性
            this.cartlist.forEach((item) => {
              if (item.selected === undefined) {
                this.$set(item, "selected", true);
              }
            });
          }
        },
        fail: (err) => {
          console.error('加载购物车数据失败', err);
        }
      });
    },
    // 计算单个超市的总价 - 只计算选中的商品
    calculateSupermarketTotal(group) {
      return group.reduce((total, item) => {
        return item.selected ? total + item.price * item.quantity : total;
      }, 0);
    },
    // 增加数量
    increaseQuantity(item) {
      item.quantity++;
      this.saveCartData();
    },
    // 减少数量
    decreaseQuantity(item) {
      if (item.quantity > 1) {
        item.quantity--;
        this.saveCartData();
      } else if (item.quantity === 1) {
        // 当数量为1时再减就变为0，移除商品
        this.removeItem(item);
      }
    },
    // 移除商品（优化版）
    removeItem(item) {
      // 使用$nextTick确保UI更新完成后再操作
      this.$nextTick(() => {
        const index = this.cartlist.findIndex((i) => i.id === item.id);
        if (index !== -1) {
          this.cartlist.splice(index, 1);
          this.saveCartData();
          uni.showToast({
            title: "已移除商品",
            icon: "success",
          });
        }
      });
    },
    // 保存购物车数据
    saveCartData() {
      const userId = uni.getStorageSync('userId');
      uni.request({
        url: Config.api_host+`/users/${userId}`,
        method: 'PATCH',
        data: {
          cart: this.cartlist
        },
        success: () => {
          console.log('购物车数据保存成功');
        },
        fail: (err) => {
          console.error('保存购物车数据失败', err);
        }
      });
    },
    // 切换单个商品的选择状态
    toggleItemSelect(item) {
      item.selected = !item.selected;
      this.saveCartData();
    },
    // 切换整个超市的选择状态
    toggleSupermarketSelect(group) {
      const allSelected = group.every((item) => item.selected);
      group.forEach((item) => {
        item.selected = !allSelected;
      });
      this.saveCartData();
    },
    // 检查整个超市是否全选
    isSupermarketSelected(group) {
      return group.every((item) => item.selected);
    },
    // 全选/取消全选
    toggleSelectAll() {
      const shouldSelectAll = !this.isAllSelected;
      this.cartlist.forEach((item) => {
        item.selected = shouldSelectAll;
      });
      this.saveCartData();
    },
    // 清空当前超市购物车方法
    clearCurrentSupermarketCart(supermarketGroup) {
      const shopId = supermarketGroup[0].shopId;
      this.cartlist = this.cartlist.filter((item) => item.shopId !== shopId);
      this.saveCartData();
      uni.showToast({
        title: "该超市购物车已清空",
        icon: "success",
      });
    },
    // 点击结算
    checkoutBySupermarket(supermarketGroup) {
      const selectedItems = supermarketGroup.filter((item) => item.selected);
      uni.setStorageSync('selectedCheckoutItems', JSON.stringify(selectedItems));
      uni.navigateTo({
        url: `/pages/orders/settlement`
      });
    },
    // 底部去结算按钮
    checkout() {
      const allSelectedItems = this.cartlist.filter((item) => item.selected);
      uni.setStorageSync('selectedCheckoutItems', JSON.stringify(allSelectedItems));
      uni.navigateTo({
        url: `/pages/orders/settlement`
      });
    },
  },
};
</script>

<style scoped>
/* 新增的选择相关样式 */
.select-all {
  padding: 12px 15px;
  background: #fff;
  margin-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

checkbox-group {
  margin-right: 10px;
}

/* 原有样式保持不变，可根据实际需求微调 */
.cart-page {
  padding-bottom: 100px;
}

.supermarket-group {
  margin: 15px;
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.supermarket-header {
  display: flex;
  justify-content: space-between;
  padding: 12px 15px;
  background: #f5f5f5;
  font-size: 16px;
}

.supermarket-name {
  font-weight: bold;
}

.supermarket-total {
  color: #e74c3c;
  display: flex;
  justify-content: space-between;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.cart-item-img {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  margin-right: 12px;
}

.cart-item-info {
  flex: 1;
}

.item-name {
  font-size: 16px;
  margin-bottom: 6px;
}

.item-price {
  color: #999;
  font-size: 14px;
  margin-bottom: 10px;
}

.item-quantity {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 28px;
  height: 28px;
  line-height: 28px;
  text-align: center;
  border: 1px solid #ddd;
  font-size: 18px;
}

.quantity-num {
  width: 40px;
  text-align: center;
  font-size: 16px;
}

.item-subtotal {
  margin: 0 15px;
  color: #e74c3c;
  font-weight: bold;
}

.delete-btn {
  color: #999;
}

.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.05);
}

.total-price {
  font-size: 16px;
  font-weight: bold;
  color: #e74c3c;
}

.checkout-button {
  background: #1aad19;
  color: #fff;
  padding: 8px 20px;
  border-radius: 20px;
  font-size: 14px;
}

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
  color: #999;
}

.empty-text {
  margin-top: 10px;
  font-size: 16px;
}
</style>    